package org.example.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

@RestController
@RequestMapping("/email")
@RefreshScope
public class EmailController {

    @Value("${email.host}")
    private String emailHost;

    @GetMapping("/{email}/{code}")
    public boolean email(@PathVariable("email") String email,
                             @PathVariable("code") String code){
        System.out.println("sent email="+email+", code="+code);
        return sendMail(email,code);
    }

    private boolean sendMail(String email,String code){
        // mock sent email
        Properties props = new Properties();
        //使用的邮件服务器类型
        props.setProperty("mail.host", emailHost);
        //使用的认证方式
        props.setProperty("mail.smtp.auth", "true");

        Authenticator authenticator = new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("somemail@163.com", "xxxxxx");
            }
        };

        Session session = Session.getInstance(props, authenticator);
        MimeMessage msg = new MimeMessage(session);
        try {
            msg.setFrom(new InternetAddress("somemail@163.com"));
            msg.setRecipients(Message.RecipientType.TO, email);
            // 设置邮件标题
            msg.setSubject("verify code");
            // 设置邮件内容
            msg.setContent("verify code is:"+code, "text/html;charset=utf-8");
            //发邮件
            Transport.send(msg);
        } catch (Exception e) {
            return true;
        }
        return true;
    }

}
